/*
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2024/1/12 15:05
@File     : route.go
@Project  : gohub
@Desc     :
*/
package bootstap

import (
	"github.com/gin-gonic/gin"
	"gohub/app/http/middlewares"
	"gohub/routes"
	"net/http"
	"strings"
)

// 注册全局中间件
func registerGlobalMiddleWare(router *gin.Engine) {
	router.Use(
		middlewares.Logger(),
		middlewares.Recovery(),
		middlewares.ForceUA(),
	)
}

// 自定义处理404
func register404Handler(router *gin.Engine) {
	router.NoRoute(func(c *gin.Context) {
		//获取请求头accept
		acceptString := c.Request.Header.Get("Accept")
		//如果请求允许html则返回html，否则返回json
		if strings.Contains(acceptString, "text/html") {
			c.String(http.StatusNotFound, "<h1>404 Page Not Found</h1>")
		} else {
			c.JSON(http.StatusNotFound, gin.H{
				"code": 404,
				"msg":  "page not found",
			})
		}
	})
}

func SetupRoute(router *gin.Engine) {
	//注册全局中间件
	registerGlobalMiddleWare(router)
	//注册api路由
	routes.RegisterApiRoutes(router)
	//注册404路由
	register404Handler(router)
}
